package services

import (
	"cas_central_server/conf"
	"net/http"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

// jwtMiddleware 创建jwt中间件
func jwtMiddleware() echo.MiddlewareFunc {
	cfg := middleware.DefaultJWTConfig
	cfg.TokenLookup = "cookie:TOKEN"
	cfg.SigningKey = []byte(conf.Config.AppSecret)
	jwt := middleware.JWTWithConfig(cfg)
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		handler := jwt(next)
		return func(c echo.Context) error {
			err := handler(c)
			if err != nil {
				e, ok := err.(*echo.HTTPError)
				if !ok {
					return err
				}
				if e.Code == http.StatusBadRequest && e.Message == "missing or malformed jwt" {
					return echo.NewHTTPError(http.StatusUnauthorized, "尚未登录！")
				}
			}
			return err
		}
	}
}

// RegisterAPIs 注册路由
func RegisterAPIs(e *echo.Echo) {
	groupDAC := e.Group("")
	groupPublic := e.Group("")
	groupPrivate := e.Group("", jwtMiddleware())
	{
		// dac devices APIs, public
		groupDAC.GET("/dacData/:dacName", receiveDataFromDACHandler)
	}
	{
		// Public APIs
		groupPublic.POST("/login", loginHandler)
	}
	{
		// Private APIs
		groupPrivate.POST("/logout", logoutHandler)
		groupPrivate.PUT("/password", changePasswordHandler)
		groupPrivate.GET("/dacDataPush", pushSampleDataToClientHandler)
		groupPrivate.GET("/detailedDacData", retrieveDetailedDataHandler)
		groupPrivate.GET("/detailedDacDataBefore", retrieveDetailedDataBeforeHandler)
		groupPrivate.GET("/detailedDacDataAfter", retrieveDetailedDataAfterHandler)
		groupPrivate.GET("/dacs", listDacsHandler)
		groupPrivate.GET("/devices", fetchDevicesHandler)
		groupPrivate.POST("/devices", updateDevicesHandler)
	}
}
